package 尚硅谷juc大厂.test4;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 案例说明：电商比价需求
 * 1：同一款产品，同时搜索出同款产品在各大电商得售价，如：同一本书在京东、拼多多、淘宝上各卖多少钱
 * 2：同一款产品，同时搜索出本产品在某一个电商平台下，各个入驻门店的售价是多少
 */
public class Test4 {

    static List<NetMall> list= Arrays.asList(
      new NetMall("京东"),
      new NetMall("淘宝"),
      new NetMall("拼多多"),
      new NetMall("天猫"),
      new NetMall("当当网"),
      new NetMall("咸鱼")
    );

    public static double calcPrice(String goodsName){
        try {
            TimeUnit.SECONDS.sleep(1);
            return ThreadLocalRandom.current().nextDouble()*2+goodsName.charAt(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 0;
    }

    //同步执行
    public static List<String> getPriceByStep(List<NetMall> list,String goodsName){
        List<String> collect = list.
                stream().
                map(v ->
                        String.format(
                                goodsName + "in %s price is %.2f",
                                v.getMallName(),
                                calcPrice(goodsName)
                        )
                ).collect(Collectors.toList());
        return collect;
    }

    //异步并发执行
    public static List<String> getPriceByAsync(List<NetMall> list,String goodsName){
        List<CompletableFuture<String>> futures = list.
                stream().
                map(v ->
                        CompletableFuture.supplyAsync(
                                () -> String.format(
                                        goodsName + " is %s price is %.2f",
                                        v.getMallName(),
                                        calcPrice(goodsName)
                                )
                        )
                ).collect(Collectors.toList());
        /**
         * join()和get()的区别：他俩都是阻塞的
         * join不会抛异常，get会抛出异常，在lamda表达式中只能用join，不能用get
         */
        List<String> collect = futures.stream().map(CompletableFuture::join).collect(Collectors.toList());
        return collect;
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        getPriceByStep(list,"mysql");
        long end = System.currentTimeMillis();
        System.out.println("执行getPriceByStep方法耗时："+(end-start));

        System.out.println("--------------------------------------------");

        long start2 = System.currentTimeMillis();
        getPriceByAsync(list,"mysql");
        long end2 = System.currentTimeMillis();
        System.out.println("执行getPriceByAsync方法耗时："+(end2-start2));
    }

}


